package com.dl.chat.synctask;

import com.dl.chat.entity.ChatHistory;
import com.dl.chat.service.ChatHistoryService;
import com.dl.chat.service.RedisService;
import jakarta.annotation.Resource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Component
public class ChatHistorySyncTask {

    @Resource
    private RedisService redisService;

    @Resource
    private ChatHistoryService chatHistoryService;

    /**
     * 每分钟同步一次 Redis 数据到 PostgreSQL
     */
    @Scheduled(fixedRate = 60000000) //
    public void syncChatHistory() {
        // 获取所有用户的对话历史
        List<String> userIds = redisService.getAllUserIds(); // 需要实现 getAllUserIds 方法
        for (String userId : userIds) {
            // 从 Redis 获取对话历史
            List<Map<String, String>> history = redisService.getChatHistory(userId);

            // 将对话历史同步到 PostgreSQL
            for (Map<String, String> entry : history) {
                ChatHistory chatHistory = new ChatHistory();
                chatHistory.setUserId(userId);
                chatHistory.setRole(entry.get("role"));
                chatHistory.setContent(entry.get("content"));
                chatHistory.setCreatedAt(LocalDateTime.now()); // 使用当前时间
                chatHistoryService.saveChatHistory(chatHistory);
            }

            // 同步完成后清空 Redis 中的对话历史
            redisService.clearChatHistory(userId);
        }
        System.out.println("定时任务：Redis 数据已同步到 PostgreSQL");
    }
}